//引入router模块
const getRouter = require('router');
//获取路由对象
//返回值是路由对象，这里和创建服务器对象相似
const router = getRouter();

//导入学生构造函数
const Student = require('../model/user');

//引入模板引擎
const template = require('art-template');

//引入querystring模块(内置的)
const querystring = require('querystring');




//呈递学生信息页面
router.get('/add', (req, res) => {
    let html = template('index.art', {});
    res.end(html);
});
//呈递学生档案列表页
router.get('/list', async(req, res) => {
    //查询所有学生信息
    let students = await Student.find();//注意返回的是数组

    let html = template('list.art', {
        //把上面查询到的数组放进来
        students:students
    });
    res.end(html);
});
//实现学生信息添加功能，post请求
router.post('/add', (req, res) => {
    //接收post请求参数
    let formData = '';
    req.on('data', param => {
        formData += param;
    });
    req.on('end', async () => {
        // console.log(formData);
        // console.log(querystring.parse(formData));
        //写成异步函数的形式
        await Student.create(querystring.parse(formData));
        res.writeHead(301, {
            Location: '/list'
        });
        res.end();
    });
    

    
});

module.exports = router;
